package home;

import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnectionClient {
    private static final String TAG = "HttpUrlClient";
    private final OnDataFetchedListener listener;

    public HttpUrlConnectionClient(OnDataFetchedListener listener) {
        this.listener = listener;
    }

    // 发起 GET 请求（异步执行）
    public void fetchData(String apiUrl) {
        new AsyncTask<String, Void, String>() {
            @Override
            protected String doInBackground(String... params) {
                HttpURLConnection connection = null;
                try {
                    // 创建 URL 对象
                    URL url = new URL(params[0]);
                    // 打开 HTTP 连接
                    connection = (HttpURLConnection) url.openConnection();
                    // 设置请求方法为 GET
                    connection.setRequestMethod("GET");
                    // 设置超时时间（毫秒）
                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(15000);
                    // 发送请求并获取响应码
                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        // 读取响应数据
                        InputStream inputStream = connection.getInputStream();
                        return readInputStream(inputStream);
                    } else {
                        Log.e(TAG, "HTTP Error: " + responseCode);
                        return null;
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Network Error: " + e.getMessage());
                    return null;
                } finally {
                    // 关闭连接
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }

            @Override
            protected void onPostExecute(String json) {
                if (listener != null) {
                    if (json != null) {
                        listener.onSuccess(json);
                    } else {
                        listener.onFailure("数据获取失败");
                    }
                }
            }
        }.execute(apiUrl);
    }

    // 读取输入流并转换为字符串
    private String readInputStream(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        reader.close();
        return stringBuilder.toString();
    }

    // 回调接口（用于传递结果）
    public interface OnDataFetchedListener {
        void onSuccess(String json);
        void onFailure(String message);
    }
}